CS 50 Dynamic Memory Allocation



the variable we need to named, mostly are at the stack.
Dynamic allocated memory comes from a pool of memory known as the heap.
Prior to this point, all memory we've been working with has been coming from a pool of memory known as the stack.

// statically obtain an integer
int x;
// dyanmically obtain an integer
int *px = malloc(4); // 8 * 4 = 32;   4bytes 32int
         // malloc(sizeof(int));

// array of floats on the stack
float stack_array[x];

// array of floats on the heap
float* heap_array = malloc(x * sizeof(float));

if you use dynamic memory allocation, you may use free(), or it will result memory leak.

char* word = malloc(50 * sizeof(char));
// do stuff with word

// now we're done working with that block
free(word);
#cs50 #heap #stack #pointer






你可能感興趣的文章

Session 機制是甚麼碗糕

Session 機制是甚麼碗糕

React-[useEffect篇]- 元件的生命週期 與 useEffect hook ,與錯誤處理

React-[useEffect篇]- 元件的生命週期 與 useEffect hook ,與錯誤處理

Day02 典型統計應用在社群媒體分析(Classical statistics applied to social data) part 2

Day02 典型統計應用在社群媒體分析(Classical statistics applied to social data) part 2






留言討論